package string.understanding;

/**
 * @Classname : BasicCalculatorII
 * @Description : 227. 基本计算器 II
 * https://leetcode.cn/problems/basic-calculator-ii/
 * @Author : chentianyu
 * @Date 2022/12/10 22:09
 */


public class BasicCalculatorII {
    public int calculate(String s) {
        char op = '+';
        int left = 0, right = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') continue;
            int[] parse = parseNum(s, i);
            int num = parse[0];
            i = parse[1];
            switch (op) {
                case '+': left += right; right = num; break;
                case '-': left += right; right = -num; break;
                case '*': right *= num; break;
                case '/': right /= num; break;
            }
            if (i < s.length()) op = s.charAt(i);
        }
        return left + right;
    }

    private int[] parseNum(String s, int i) {
        int num = 0;
        while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
            num = num * 10 + s.charAt(i++) - '0';
        }
        return new int[]{num, i};
    }
}
